
var app = getApp()
var Bmob = require('../../utils/bmob.js');
Page({
  data: {
    isReEdit: false,
    shopId: '',
    franchiseeId: '',
    startTime: '00:00',
    endTime: '23:59',
    shopImg: [],
    IDCardImg: [],
    BlicenseImg: [],
    OlicenseImg: [],
    facilities : [
      { name: 'WIFI', value: '1', checked: false },
      { name: '停车位', value: '2', checked: false },
      { name: '微信支付', value: '3', checked: false },
      { name: '支付宝', value: '4', checked: false },
      // { name: '其他', value: '5', checked: false }
    ],
    cdnUrl: 'http://cdn.jisuapp.cn',
    tplUrls : [
      'http://cdn.jisuapp.cn' + '/static/webapp/images/franchisee/tpl-1.jpg',
      'http://cdn.jisuapp.cn' + '/static/webapp/images/franchisee/tpl-2.jpg',
      'http://cdn.jisuapp.cn' + '/static/webapp/images/franchisee/tpl-3.jpg',
      'http://cdn.jisuapp.cn' + '/static/webapp/images/franchisee/tpl-4.jpg',
    ],
    tplId: 0,
    tplHidden : true,
    tplDetailHidden: true,
    tplText: ['门店', '外卖', '商城', '到店'],
    chooseTplId: '',
    regionList: [],
    region: [0, 0, 0],
    address: '',
    categoryList: [],
    categoryIndex: -1,
    industryList: [],
    industryIndex: -1,
    shopLogo: '',
    longitude: '',
    latitude: '',
    franchiseeInfo: {},
    appShopInfo: {}
  },
  onLoad: function(options){
    let franchiseeId = options.franchisee_id || '';
    let shopId = options.shop_id || '';
    let edit = options.edit || '';
    let type = options.type || 0;
   
    this.setData({
      franchiseeId: franchiseeId,
      shopId: shopId,
      isReEdit: true,
      type : type
    });
    
    if (this.data.isReEdit){
      app.setPageTitle('编辑资料');
      this.getAppShopCateList();
    }else{
      this.getOldTpl();
    }
   // this.getAppShopInfo();
  },
  getAppShopCateList: function () {
    let that = this;

    var categoryList = Bmob.Object.extend("categroyList");
    var categoryList = new Bmob.Query(categoryList);
    var Franchisee = Bmob.Object.extend("Franchisee");
    var franchisee = new Franchisee();
    franchisee.id = "86cyg11I";
    categoryList.equalTo("franchisee", franchisee);
    categoryList.find({
      success: function (data) {
        var categoryList = that.data.categoryList;
        for (var i = 0; i < data.length; i++) {
          var category = { category: 0, name: '全部' }
          category.category = data[i].get("categroy");
          category.name = data[i].get("name");
          categoryList.push(category)
        }
        var data = {};
        data.categoryList = categoryList
        that.setData(data);
        that.getSubShopData();
      }



    })
    
  },
  // 完善信息保存
  enterSubmit : function(e){
    let that = this;
    let val = e.detail.value;
    let param = {
      business_time: [{
        start_time: val.start_time,
        end_time: val.end_time
      }],
      description: val.description,
      per_capita: val.per_capita,
      shop_facility: val.shop_facility
    };
    
    //param.mode_id = that.data.chooseTplId;
   // param.parent_app_id = app.getAppId();
    param.app_id = that.data.franchiseeId;
    //param.shop_id = that.data.shopId;
    param.type = 0;
    param.carousel_imgs = that.data.shopImg;
    //let IDCardImg = that.data.IDCardImg;
    //let BlicenseImg = that.data.BlicenseImg;
   // let OlicenseImg = that.data.OlicenseImg;
    //param.certif_pics = [IDCardImg,BlicenseImg, OlicenseImg];
/*
    if (!param.mode_id) {
      app.showModal({
        content: '请选择模板'
      });
      return;
    }*/
    if (!param.business_time[0].start_time || !param.business_time[0].end_time) {
      app.showModal({
        content: '请输入营业时间'
      });
      return;
    }
    if (!param.description) {
      app.showModal({
        content: '请输入门店介绍'
      });
      return;
    }
    if (!param.carousel_imgs.length) {
      app.showModal({
        content: '请上传店铺环境图片'
      });
      return;
    }
    if (param.per_capita && (!/(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(param.per_capita))){
      app.showModal({
        content: '请输入正确的人均消费'
      });
      return;
    }

    app.sendRequest({
      url: '/index.php?r=AppShop/UpdateAppSubShop',
      data: param,
      method: 'POST',
      success: function (res) {
        app.showToast({
          title: '保存成功',
          icon: 'success'
        });
        let pages = getCurrentPages();
        for (let i = 0; i < pages.length; i++) {
          if (pages[i].page_router) {
            app.globalData['franchiseeTplChange-' + pages[i].page_router] = true;
          }
        }
        let tabBarPagePathArr = app.getTabPagePathArr();
        for (let i = 0; i < tabBarPagePathArr.length; i++) {
          let router = tabBarPagePathArr[i].split('/')[2];
          if (router) {
            app.globalData['franchiseeTplChange-' + router] = true;
          }
        }
        app.turnToPage("/franchisee/pages/franchiseeEnterStatus/franchiseeEnterStatus?franchisee_id=" + that.data.franchiseeId , true);
      }
    })
  },
  // 上传照片
  uploadLicenseImg: function (e) {
    let that = this;
    let length = e.currentTarget.dataset.length || 6;
    let field = e.currentTarget.dataset.field;
    let num = length - that.data[field].length;
    app.chooseImage(function (res) {
      console.log(res);
      let newdata = {};
      newdata[field] = that.data[field].concat(res);
      that.setData(newdata);
    }, num);
  },
  // 删除照片
  deleteLicenseImg: function (e) {
    let index = e.currentTarget.dataset.index;
    let field = e.currentTarget.dataset.field;
    let img = this.data[field];

    img.splice(index, 1);
    let newdata = {};
    newdata[field] = img;
    this.setData(newdata);
  },
  // 营业时间-开始
  bindStartTimeChange: function(e){
    this.setData({
      startTime: e.detail.value
    })
  },
  // 营业时间-结束
  bindEndTimeChange: function (e) {
    this.setData({
      endTime: e.detail.value
    })
  },
  // 店内设施多选框修改
  facilitiesCheckboxChange : function(e){
    // console.log('checkbox发生change事件，携带value值为：', e.detail.value)
  },
  // 预览图片
  previewImage: function(e){
    let src = e.currentTarget.dataset.src;

    app.previewImage({
      current: src
    });
  },
  // 选择模板弹窗显示
  tplPopShow: function(){
    this.setData({
      tplHidden: false
    });
  },
  // 选择模板弹窗隐藏
  tplPopHidden: function(){
    this.setData({
      tplHidden: true
    });
  },
  // 模板详情弹窗显示
  tplDetailShow: function (e) {
    let id = e.currentTarget.dataset.id;
    this.setData({
      tplDetailHidden: false,
      tplId: id
    });
  },
  // 模板详情弹窗隐藏
  tplDetailHidden: function () {
    this.setData({
      tplDetailHidden: true
    });
  },
  // 确认选择模板
  tplDetailConfirm: function(){
    let that = this;
    this.setData({
      tplHidden: true,
      tplDetailHidden: true,
      chooseTplId: that.data.tplId
    });
    if (that.data.tplId == 1){
      app.showModal({
        content: '外卖商品未绑定分类将无法显示'
      });
    } else if (that.data.tplId == 3) {
      app.showModal({
        content: '到店商品未绑定分类将无法显示'
      });
    }
  },
  // 上传logo
  uploadLogo: function () {
    let that = this;
    app.chooseImage(function (res) {
      that.setData({
        shopLogo: res[0]
      });
    }, 1);
  },
  // 获取定位
  getLocation: function () {
    let that = this;
    app.chooseLocation({
      success: function (res) {

        app.sendRequest({
          url: '/index.php?r=Map/getAreaInfoByLatAndLng',
          data: {
            longitude: res.longitude,
            latitude: res.latitude
          },
          success: function (data) {
            let province = data.data.address_component.province;
            let city = data.data.address_component.city;
            let district = data.data.address_component.district;

            that.textToRegion(province, city, district);
          }
        });

        that.setData({
          address: res.name || '',
          longitude: res.longitude,
          latitude: res.latitude
        });

      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  // 获取地区
  areaList: [],
  getArea: function (successfn) {
    let that = this;

    app.sendRequest({
      url: '/index.php?r=AppShop/getAllRegionInfo',
      data: {},
      success: function (res) {
        let list = res.data;
        let provinceArr = [];
        let cityArr = [];
        let townArr = [];
        let newdata = {};

        that.areaList = list;

        for (let i in list) {
          provinceArr.push({
            id: list[i].id,
            name: list[i].name,
            parent_id: list[i].parent_id
          });
        }

        cityArr = that.getCity();
        townArr = that.getTown();

        newdata['regionList[0]'] = provinceArr;
        newdata['regionList[1]'] = cityArr;
        newdata['regionList[2]'] = townArr;

        that.setData(newdata);

        typeof successfn === 'function' && successfn(res);
      }
    });
  },
  // 获取对象的第一个元素
  getObjectFirst: function (obj) {
    for (let i in obj) {
      return obj[i];
    }
  },
  // 根据省，获取市
  // 如果不传provinceId ， 则获取对象的第一个省的市
  getCity: function (provinceId) {
    let that = this;
    let cities = {};
    let cityArr = [];

    if (provinceId) {
      cities = that.areaList[provinceId].cities;
    } else {
      cities = (that.getObjectFirst(that.areaList)).cities;
    }
    for (let i in cities) {
      cityArr.push({
        id: cities[i].id,
        name: cities[i].name,
        parent_id: cities[i].parent_id
      });
    }

    return cityArr;
  },
  // 根据省、市，获取区
  // 如果不传 provinceId， 则获取对象的第一个省的第一个市的区
  // 如果传 cityId，则必须传provinceId
  // 如果传 provinceId ，不传 cityId， 则获取这个省的第一个市的区
  getTown: function (provinceId, cityId) {
    let that = this;
    let cities = {};
    let towns = {};
    let townArr = [];

    if (cityId && !provinceId) {
      console.log('如果有传cityId， 则provinceId 是必须传的');
      return;
    }
    if (provinceId) {
      cities = that.areaList[provinceId].cities;
    } else {
      cities = (that.getObjectFirst(that.areaList)).cities;
    }

    if (cityId) {
      towns = cities[cityId].towns;
    } else {
      towns = (that.getObjectFirst(cities)).towns;
    }

    for (let i in towns) {
      townArr.push({
        id: towns[i].id,
        name: towns[i].name,
        parent_id: towns[i].parent_id
      });
    }

    return townArr;
  },
  // 根据省市区 显示 店铺位置
  textToRegion: function (province, city, district) {
    let that = this;
    let provinces = that.data.regionList[0];
    let region = that.data.region;
    let provinceId = '';
    let cityId = '';
    let newdata = {};
    let cities = [];
    let towns = [];

    for (let i = 0; i < provinces.length; i++) {
      if (province == provinces[i].name) {
        region[0] = i;
        provinceId = provinces[i].id;
        break;
      }
    }

    cities = that.getCity(provinceId);
    for (let i = 0; i < cities.length; i++) {
      if (city == cities[i].name) {
        region[1] = i;
        cityId = cities[i].id;
        break;
      }
    }

    towns = that.getTown(provinceId, cityId);
    for (let i = 0; i < towns.length; i++) {
      if (district == towns[i].name) {
        region[2] = i;
        break;
      }
    }

    newdata['regionList[1]'] = cities;
    newdata['regionList[2]'] = towns;
    newdata.region = region;

    that.setData(newdata);
  },
  // 省市区选择器改变
  bindRegionColumnChange: function (e) {
    let that = this;
    let column = e.detail.column;
    let value = e.detail.value;
    let newdata = {};
    let regionList = that.data.regionList;

    newdata.region = that.data.region;
    newdata.region[column] = value;

    if (column == 0) {
      let provinceId = regionList[0][value].id;
      let city = that.getCity(provinceId);
      let town = that.getTown(provinceId);

      newdata['regionList[1]'] = city;
      newdata['regionList[2]'] = town;
      newdata.region[1] = 0;
      newdata.region[2] = 0;
    } else if (column == 1) {
      let provinceIndex = that.data.region[0];
      let provinceId = regionList[0][provinceIndex].id;
      let cityId = regionList[1][value].id;
      let town = that.getTown(provinceId, cityId);

      newdata['regionList[2]'] = town;
      newdata.region[2] = 0;
    }

    that.setData(newdata);

  },
  // 行业分类选择器改变
  bindIndustryChange: function(e) {
    this.setData({
      industryIndex: e.detail.value
    })
  },
  // 店铺分类选择器改变
  bindCategoryChange: function (e) {
    this.setData({
      categoryIndex: e.detail.value
    })
  },
  // 获取行业分类
  getIndustryType: function (successfn) {
    let that = this;

    app.sendRequest({
      url: '/index.php?r=AppShop/GetIndustryAndBussinessType',
      data: {
      },
      success: function (res) {
        let industry = res.data.industry;
        let cate = [];
        for (let i in industry) {
          cate.push({
            id: i,
            name: industry[i]
          });
        }
        that.setData({
          industryList: cate
        });
        typeof successfn === 'function' && successfn(res);
      }
    });
  },
  // 获取店铺分类
  getAppShopCateList1: function (successfn) {
    let that = this;

    app.sendRequest({
      url: '/index.php?r=AppShop/GetAppShopCateList',
      data: {
        common_type: 1,
        form: 'app_shop'
      },
      success: function (res) {
        let catelist = res.data;
        let cate = [];
        for (let i = 0; i < catelist.length; i++) {
          cate.push({
            id: catelist[i].id,
            name: catelist[i].name
          });
        }
        that.setData({
          categoryList: cate
        });
        typeof successfn === 'function' && successfn(res);
      }
    });
  },
  // 重新编辑保存
  reEditSubmit: function(e){
    let that = this;
    let val = e.detail.value;
   let franchiseeId = that.data.franchiseeId;
      //param.parent_app_id = app.getAppId();
    //param.app_id = that.data.franchiseeId;
    //param.shop_id = that.data.shopId;
  
  //  param.industry_type = that.data.industryIndex == -1 ? '' : that.data.industryList[that.data.industryIndex].id;

    //param.mode_id = that.data.chooseTplId;

    //param.type = that.data.type == 2 ? 2 : 1;
    //let IDCardImg = that.data.IDCardImg;
    //let BlicenseImg = that.data.BlicenseImg;
    //let OlicenseImg = that.data.OlicenseImg;
   // param.certif_pics = [IDCardImg, BlicenseImg, OlicenseImg];
    var name = val.name,
      phone = val.phone,
      address_detail = val.address_detail,
      business_time = [{
        start_time: val.start_time,
        end_time: val.end_time
      }],
      description = val.description,
      address={},
      businesstime=[],
      regionList = that.data.regionList,
      region = that.data.region,
      per_capita = val.per_capita;
      
    var picture = that.data.shopLogo;
    var category = that.data.categoryIndex;
    var longitude = that.data.longitude;
    var latitude = that.data.latitude;
   var county_id = that.data.regionList[2][that.data.region[2]].id;
    var carousel_imgs = that.data.shopImg;
   
    if (!name) {
      app.showModal({
        content: '请输入店铺名称'
      });
      return;
    }
    if (!picture) {
      app.showModal({
        content: '请上传店铺logo'
      });
      return;
    }
    if (!longitude) {
      app.showModal({
        content: '请去定位一下店铺位置'
      });
      return;
    }
    if (!address_detail) {
      app.showModal({
        content: '请填写详细地址'
      });
      return;
    }
    if (!phone) {
      app.showModal({
        content: '请输入门店客服电话'
      });
      return;
    }
    if (!/^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/.test(phone) && !/^(\d{3,4}-?)?\d{7,8}$/.test(phone)) {
      app.showModal({
        content: '请输入正确的客服电话'
      });
      return;
    }
    /*    if (!param.industry_type) {
      app.showModal({
        content: '请选择行业分类'
      });
      return;
    }*/
    if (that.data.categoryList.length > 0 && category.length <= 0) {
      app.showModal({
        content: '请选择店铺分类'
      });
      return;
    }
    if (!description) {
      app.showModal({
        content: '请输入门店介绍'
      });
      return;
    }
    if (!carousel_imgs.length) {
      app.showModal({
        content: '请上传店铺环境图片'
      });
      return;
    }
    if (per_capita && (!/(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(per_capita))) {
      app.showModal({
        content: '请输入正确的人均消费'
      });
      return;
    }
    address.province_name = regionList[0][region[0]].name;
    address.city_name = regionList[1][region[1]].name;
    address.county_name = regionList[2][region[2]].name;
    address.detail = address_detail;
    var time={}
    time.start_time = that.data.startTime;
time.end_time = that.data.endTime;
    businesstime.push(time);
    var Franchisee = Bmob.Object.extend("Franchisee");
    var franchisee = new Bmob.Query(Franchisee);
    var currentUser = Bmob.User.current();
    var objectId = currentUser.id;
    var isme = new Bmob.User();
    isme.id = objectId;
  
    franchisee.get(franchiseeId , {
      success: function (result) {
        console.log("fjdksljal")
        // 回调中可以取得这个 GameScore 对象的一个实例，然后就可以修改它了
        result.set("Franchisee_title", name);
        result.set("Franchisee_phone", phone);
        result.set("Franchisee_address", address);
        result.set("img_url", picture);
        result.set("Franchisee_type", that.data.categoryList[category].category);
        result.set("business_time", businesstime);
        result.set("longitude", longitude);
        result.set("latitude", latitude);
        result.set("description", description);
        result.set("per_capita", per_capita);
        result.set("carousel_imgs", carousel_imgs);
        result.set("is_audit", 1);
        result.set("user", isme);
        result.set("hot", 0);
        result.save(null,{
success(res){
  app.showToast({
    title: '保存成功',
    icon: 'success'
  });

  app.turnToPage("/pages/franchiseeEnterStatus/franchiseeEnterStatus?franchisee_id=" + that.data.franchiseeId, true);
}


        });

        // The object was retrieved successfully.
      },
      error: function (error) {
console.log(error)
      }
    });
    //添加数据，第一个入口参数是null
    /*
    app.sendRequest({
      url: '/index.php?r=AppShop/UpdateAppSubShop',
      data: param,
      method: 'POST',
      success: function (res) {
        app.showToast({
          title: '保存成功',
          icon: 'success'
        });
        if (that.data.type == 2){
          app.globalData.franchiseeListRefresh = true;
        }
        let pages = getCurrentPages();
        for (let i = 0; i < pages.length; i++) {
          if (pages[i].page_router) {
            app.globalData['franchiseeTplChange-' + pages[i].page_router] = true;
          }
        }
        let tabBarPagePathArr = app.getTabPagePathArr();
        for (let i = 0; i < tabBarPagePathArr.length; i++) {
          let router = tabBarPagePathArr[i].split('/')[2];
          if (router) {
            app.globalData['franchiseeTplChange-' + router] = true;
          }
        }
        app.turnToPage("/franchisee/pages/franchiseeEnterStatus/franchiseeEnterStatus?franchisee_id=" + that.data.franchiseeId, true);
      }
    })*/
  },
  // 获取旧数据
  getSubShopData: function () {
    var that = this;
    var Franchisee = Bmob.Object.extend("Franchisee");
    var franchisee = new Bmob.Query(Franchisee);
    var franchiseeId=that.data.franchiseeId;
   
   
  
     franchisee.get(franchiseeId,{
      success: function (res) {
        //var goods=res;
        let categoryList = that.data.categoryList;
        let category = res.get("Franchisee_type") ? res.get("Franchisee_type") : 0;
        var categoryIndex;
        for (let i = 0; i < categoryList.length; i++) {
          if (categoryList[i].category == category) {
            categoryIndex = i;
            break;
          }
        }
       var business_time = res.get("business_time");
        var franchisee_address = res.get("Franchisee_address");
        that.setData({
          franchiseeInfo:res,
          address: franchisee_address.detail,
          shopLogo:res.get("img_url"),
          category:res.get("Franchisee_type"),
          longitude: res.get("longitude"),
          latitude: res.get("latitude"),
          categoryIndex: categoryIndex,
          shopImg: res.get("carousel_imgs"),
        startTime : business_time&& business_time.length ? business_time[0].start_time : '00:00',
          endTime :business_time && business_time.length ? business_time[0].end_time : '23:59'
        })
          that.getArea(function () {
            that.textToRegion(res.get("Franchisee_address").province_name, res.get("Franchisee_address").city_name, res.get("Franchisee_address").county_name);
          });

      },
      complete: function () {

      }
    });
    
    /*
    app.sendRequest({
      url: '/index.php?r=AppShop/GetSubShopData',
      data: {
        parent_app_id: app.getAppId(),
        app_id: that.data.franchiseeId,
        shop_id: that.data.shopId,
        p_u: app.globalData.p_u || ''
      },
      success: function (res) {
        let data = res.data[0];
        let newdata = {};
        data.description = data.description ? data.description.replace(/\n|\\n/g, '\n') : data.description;

        newdata.franchiseeInfo = data;
        newdata.shopLogo = data.picture;
        newdata.longitude = data.longitude;
        newdata.latitude = data.latitude;
        newdata.address = data.address_detail;
        newdata.chooseTplId = +data.mode_id;
        newdata.startTime = data.business_time && data.business_time.length ? data.business_time[0].start_time : '00:00';
        newdata.endTime = data.business_time && data.business_time.length ? data.business_time[0].end_time : '23:59';
        newdata.shopImg = data.carousel_imgs;
        newdata.IDCardImg = data.certif_pics[0] || [];
        newdata.BlicenseImg = data.certif_pics[1] || [];
        newdata.OlicenseImg = data.certif_pics[2] || [];

        let facilities = that.data.facilities;
        for (let i = 0; i < facilities.length; i++){
          if (data.shop_facility.indexOf( facilities[i].value ) > -1){
            newdata['facilities['+i+'].checked'] = true;
          }
        }

        that.setData(newdata);

        that.getAppShopCateList(function(){
          let categoryList = that.data.categoryList;
          let newdata2 = {};
          let category = data.category ? data.category[0] : '';
          for (let i = 0; i < categoryList.length; i++) {
            if (categoryList[i].id == category) {
              newdata2.categoryIndex = i;
              break;
            }
          }
          that.setData(newdata2);
        });
        that.getIndustryType(function(){
          let industryList = that.data.industryList;
          let newdata2 = {};
          for (let i = 0; i < industryList.length; i++) {
            if (industryList[i].id == data.industry_type) {
              newdata2.industryIndex = i;
              break;
            }
          }
          that.setData(newdata2);
        });
        that.getArea(function(){
          that.textToRegion(data.province_name, data.city_name, data.county_name);
        });
        
      }
    });*/
  },
  // 完善信息获取已有的模板
  getOldTpl : function(){
    var that = this;
    app.sendRequest({
      url: '/index.php?r=AppShop/GetSubShopData',
      data: {
        parent_app_id: app.getAppId(),
        app_id: that.data.franchiseeId,
        shop_id: that.data.shopId,
        p_u: app.globalData.p_u || ''
      },
      success: function (res) {
        let data = res.data[0];
        let newdata = {};
        newdata.chooseTplId = +data.mode_id;
        that.setData(newdata);
      }
    });
  },
  // 拨打电话
  makePhoneCall: function (e) {
    var phone = e.currentTarget.dataset.phone;
    app.makePhoneCall(phone);
  },
  // 获取总店的信息
  getAppShopInfo: function () {
    let that = this;

    app.sendRequest({
      url: '/index.php?r=AppShop/GetAppShopInfo',
      data: {
      },
      success: function (res) {
        that.setData({
          appShopInfo: res.data
        });
      }
    });
  }
})
